package com.czb.czbmybatis.sqlsession;

import com.czb.entity.Monster;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: 陈正彬
 */
public class CzbExecutor implements Executor{

    private CzbConfiguration czbConfiguration = new CzbConfiguration();

    /**
     * 工具sql查询结果
     * @param sql
     * @param parameter
     * @return
     * @param <T>
     */
    @Override
    public <T> T query(String sql, Object parameter) {
        //得到连接
        Connection connection = getConnection();
        //查询返回的结果集
        ResultSet set = null;
        PreparedStatement pre = null;

        try {
            pre = connection.prepareStatement(sql);
            //设置参数，如果参数多，可以用数组来处理
            pre.setString(1,parameter.toString());
            set = pre.executeQuery();
            //把set数据封装到对象-monster
            //这里做了简化处理，返回的结果就是一个monster记录，
            //完善的写法是一套反射机制
            Monster monster = new Monster();
            //遍历结果集,把数据封装到monster对象
            while (set.next()) {
                monster.setId(set.getInt("id"));
                monster.setAge(set.getInt("age"));
                monster.setName(set.getString("name"));
                monster.setGender(set.getInt("gender"));
                monster.setBirthday(set.getDate("birthday"));
                monster.setSalary(set.getDouble("salary"));
                monster.setEmail(set.getString("email"));
            }
            return (T)monster;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (set != null) {
                    set.close();
                }
                if (pre != null) {
                    pre.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //编写方法，通过CzbConfiguration，防护连接
    private Connection getConnection(){
        Connection connection = czbConfiguration.build("czb_mybatis.xml");
        return connection;
    }
}
